import time
import traceback
import platform
from selenium import webdriver


class SeleniumRequest(object):
    def __init__(self):
        self.browser = None
        self.cookies = None
    
    @property
    def platform(self):
        platform_info = platform.platform()
        if "Darwin" in platform_info:
            result = "Mac"
        elif "inux" in  platform_info:
            result = "Linux"
        else:
            result = "Win"
        return result
    
    def set_options(self, *args):
        options = webdriver.ChromeOptions()
        if isinstance(args, str):
            options.add_argument(args)
        elif isinstance(args, tuple):
            for i in args:
                options.add_argument(i)
        else:
            pass
        # option.add_argument("--disable-gpu")
        options.add_argument("--no-sandbox")
        options.add_argument("--disable-dev-shm-usage")
        options.add_experimental_option("excludeSwitches", ['enable-automation'])
        options.add_argument("--headless")
        if self.platform == "Darwin":
            self.browser = webdriver.Chrome(options=options)
        elif self.platform == "Linux":
            options.binary_location = "/usr/bin/google-chrome-stable"
            excutable_path = "/opt/google/chromedriver"
            self.browser = webdriver.Chrome(excutable_path=excutable_path, opthions=options)
    
    def scroll_to_bottom(self):
        js = "var q=document.documentElement.scrollTop=100000"
        self.browser.execute_script(js)
    
    def fetch_cookies(self):
        cookie_list = self.browser.get_cookies()
        self.cookies = []
        for cookie in cookie_list:
            new_cookie = dict()
            new_cookie["name"] = cookie["name"]
            new_cookie["value"] = cookie["value"]
            new_cookie["expiry"] = cookie.get("expiry")
            self.cookies.append(new_cookie)
        return self.cookies
    
    def fetch_html(self, url, *args, **kwargs):
        if not self.browser:
            self.set_browser(*args)
            
        failure_times = 0
        while True:
            try:
                self.browser.get(url)
                self.fetch_cookie()
                print("cookies: ", self.cookies)
                if kwargs.get("scroll") is True:
                    self.scroll_to_bottom()
                resp = self.browser.page_source
                self.browser.quit()
                break
            except Exception:
                failure_times += 1
                self.browser.quit()
                resp = ""
                print(str(traceback.format_exc()))
                time.sleep(1)
                if failure_times >= 8:
                    break
        return resp
